/*
 * Copyright (C) 2007-2008  Hylke van der Schaaf
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, in version 3 of the License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package hextd.message;

import com.twolattes.json.Json;
import com.twolattes.json.Marshaller;
import com.twolattes.json.TwoLattes;
import hextd.message.MessageFactory.NetworkMessage;
import hextd.server.PlayerInfo;
import java.util.regex.Pattern;

public class MessagePlayerInfo implements Message {

	private static Marshaller<PlayerInfo> marshaller;
	public NetworkMessage type = NetworkMessage.PlayerInfo;
	public static String key = "MPI";
	public static Pattern MessagePattern = Pattern.compile(key + ".*");
	//
	private String message;
	private PlayerInfo playerInfo;

	public static String formatMessage(PlayerInfo playerInfo) {
		return key + marshaller.marshall(playerInfo).toString();
	}

	public MessagePlayerInfo() {
		if (marshaller == null) {
			marshaller = TwoLattes.createMarshaller(PlayerInfo.class);
		}
	}

	private MessagePlayerInfo(String message) {
		if (marshaller == null) {
			marshaller = TwoLattes.createMarshaller(PlayerInfo.class);
		}
		this.message = message;
		Json.Value fromString = Json.fromString(message.substring(key.length()));
		playerInfo = marshaller.unmarshall((Json.Object) fromString);
	}

	@Override
	public String getMessage() {
		return this.message;
	}

	@Override
	public Message initFromString(String message) {
		return new MessagePlayerInfo(message);
	}

	@Override
	public int getSenderId() {
		return -2;
	}

	public PlayerInfo getPlayerInfo() {
		return playerInfo;
	}

	@Override
	public void setSenderId(int id) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public Pattern getPattern() {
		return MessagePlayerInfo.MessagePattern;
	}

	@Override
	public NetworkMessage getType() {
		return this.type;
	}
}
